package com.aos.eap.activity;

import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aos.eap.R;
import com.aos.eap.adapter.AlarmInfoListAdapter;
import com.aos.eap.base.BaseDialogActivity;
import com.aos.eap.base.Constant;
import com.aos.eap.bean.AskRepairBean;
import com.aos.eap.bean.AskRepairFaultBean;
import com.aos.eap.bean.net.BaseResponseBean;
import com.aos.eap.utils.MyUtils;
import com.aos.eap.utils.NetUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

public class MFG_AskRepairActivity extends BaseDialogActivity {


    @BindView(R.id.tvUser)
    TextView tvUser;
    @BindView(R.id.etEqpId)
    FreeUI_ClearEditText etEqpId;
    @BindView(R.id.tvType)
    TextView tvType;
    @BindView(R.id.ivTypeArrow)
    ImageView ivTypeArrow;
    @BindView(R.id.flType)
    FrameLayout flType;
    @BindView(R.id.tvLevel)
    TextView tvLevel;
    @BindView(R.id.ivLevelArrow)
    ImageView ivLevelArrow;
    @BindView(R.id.flLevel)
    FrameLayout flLevel;
    @BindView(R.id.tvDesc)
    TextView tvDesc;
    @BindView(R.id.ivDescArrow)
    ImageView ivDescArrow;
    @BindView(R.id.flDesc)
    FrameLayout flDesc;
    @BindView(R.id.etRemark)
    FreeUI_ClearEditText etRemark;
    @BindView(R.id.etLotId)
    FreeUI_ClearEditText etLotId;
    @BindView(R.id.etBdId)
    FreeUI_ClearEditText etBdId;
    @BindView(R.id.tvBdVersion)
    TextView tvBdVersion;
    @BindView(R.id.rvAlarmList)
    RecyclerView rvAlarmList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    private AskRepairBean askRepairBean;
    private FreeUI_GeneralPop typePop, levelPop, descPop;
    private AlarmInfoListAdapter alarmInfoListAdapter;
    //private LotInfoBean lotInfoBean;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_ask_repair;
    }

    @Override
    protected void initView() {
        tvUser.setText(Constant.CURRENT_USER);
        rvAlarmList.setLayoutManager(new LinearLayoutManager(MFG_AskRepairActivity.this));
        rvAlarmList.setItemAnimator(new DefaultItemAnimator());
        rvAlarmList.addItemDecoration(new DividerItemDecoration(MFG_AskRepairActivity.this, 1));
        alarmInfoListAdapter = new AlarmInfoListAdapter(null);
        alarmInfoListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        alarmInfoListAdapter.isFirstOnly(true);
        rvAlarmList.setAdapter(alarmInfoListAdapter);
        MyUtils.setEditTextListener(etEqpId, this, this::requestInfoByEqpId);
        MyUtils.setEditTextListener(etLotId, this, s -> MyUtils.setEditTextFocus(etBdId));

        etBdId.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (start == 0 && before == 0 && count > 1) {
                    if (s.length() > 0) {
                        String[] values = s.toString().split(";");
                        if (values.length > 1) {
                            etBdId.setText(values[0]);
                            tvBdVersion.setText(values[1]);
                        }
                    } else {
                        showToast("扫描信息有误", false);
                    }
                }
                if (s.length() == 0) {
                    tvBdVersion.setText("");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void requestInfoByEqpId(String eqpId) {
        JsonObject map = new JsonObject();
        map.addProperty("EqpID", eqpId);
        NetUtils.requestGetNet(this, "EMS_RepairCallLoad", map, new FreeUI_DialogEntityCallBack<BaseResponseBean<AskRepairBean>>(
                new TypeToken<BaseResponseBean<AskRepairBean>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<BaseResponseBean<AskRepairBean>> response) {
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    askRepairBean = response.body().getResponse().getBody();
                    setPageData(askRepairBean);
                } else {
                    askRepairBean = null;
                    setPageData(new AskRepairBean());
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<AskRepairBean>> response) {
                super.onError(response);
                uploadLog(response.getException());
                loadError(response.getException(), "EMS_RepairCallLoad");
                askRepairBean = null;
                setPageData(new AskRepairBean());
            }
        });
    }

    private void setPageData(AskRepairBean askRepairBean) {
        etLotId.setText(askRepairBean.getLotID());
        etBdId.setText(askRepairBean.getBDID());
        tvBdVersion.setText(askRepairBean.getBDVer());
        if (askRepairBean.getLotID().length() > 0) {
            if (askRepairBean.getBDID().length() > 0) {
                etBdId.setEnabled(false);
            } else {
                etBdId.setEnabled(true);
            }
        } else {
            etBdId.setEnabled(true);
        }
        List<String> stringList = new ArrayList<>();
        for (AskRepairFaultBean typeBean : askRepairBean.getRepairTypeList()) {
            stringList.add(typeBean.getRepairType());
        }
        typePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flType.getWidth(),
                stringList, ivTypeArrow, (s, i) -> {
                    tvType.setText(s);
                    setFaultPop((askRepairBean.getRepairTypeList().get(i).getFaultDescList()));
                });
        alarmInfoListAdapter.setNewData(askRepairBean.getALARM_ID_LIST());
    }


    private void setFaultPop(List<String> descList) {
        descPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flDesc.getWidth(),
                descList, ivDescArrow, (s, i) -> {
                    tvDesc.setText(s);
                });
    }
//    private void requestInfoByLotId(String lotId) {
//        JsonObject map = new JsonObject();
//        map.addProperty("LotID", lotId);
//        NetUtils.requestGetNet(this, "EMS_GetLotInfo", map, new FreeUI_DialogEntityCallBack<BaseResponseBean<LotInfoBean>>(
//                new TypeToken<BaseResponseBean<LotInfoBean>>() {
//                }.getType(), getSupportFragmentManager(), this) {
//            @Override
//            public void onSuccess(Response<BaseResponseBean<LotInfoBean>> response) {
//                if (response.body().isSuccess(getApplicationContext(), true)) {
//                    lotInfoBean = response.body().getResponse().getBody();
//                    tvBdId.setText(lotInfoBean.getBDID());
//                }
//            }
//
//            @Override
//            public void onError(Response<BaseResponseBean<LotInfoBean>> response) {
//                super.onError(response);
//                loadError(response.getException(), "EMS_GetLotInfo");
//            }
//        });
//    }

    @Override
    protected void initData() {

    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("报修");
        freeUI_titleView.setLeftListener(view -> showBackDialog(MFG_AskRepairActivity.this));
        freeUI_titleView.setRightListener("提交", v -> {
            if (MyUtils.isFastClick()){
                showToast("您点击的太快了",false);
                return;
            }
            if (askRepairBean == null) {
                showToast("未获取到页面信息，请重新扫描设备编号", false);
                MyUtils.setEditTextFocus(etEqpId);
                etEqpId.setText("");
                return;
            }
            String type = tvType.getText().toString().trim();
            if (FreeApi_StringUtils.isEmpty(type)) {
                showToast("请选择维修类型", false);
                return;
            }
            String level = tvLevel.getText().toString().trim();
            if (FreeApi_StringUtils.isEmpty(level)) {
                showToast("请选择优先级", false);
                return;
            }
            String desc = tvDesc.getText().toString().trim();
            if (FreeApi_StringUtils.isEmpty(desc)) {
                showToast("请选择故障描述", false);
                return;
            }
            if (FreeApi_StringUtils.isEmpty(etLotId.getText().toString())) {
                showToast("请扫描批次编号获取相关信息后再提交", false);
                MyUtils.setEditTextFocus(etLotId);
                return;
            }
            String bdId = etBdId.getText().toString().trim();
            if (FreeApi_StringUtils.isEmpty(bdId)) {
                showToast("请扫描BD编号", false);
                return;
            }
            String bdVer = tvBdVersion.getText().toString().trim();
            if (FreeApi_StringUtils.isEmpty(bdVer)) {
                showToast("请扫描BD编号获取BD版本", false);
                return;
            }
            JsonObject map = new JsonObject();
            map.addProperty("EqpID", askRepairBean.getEqpID());
            map.addProperty("LotID", etLotId.getText().toString());
            map.addProperty("UserID", Constant.CURRENT_USER);
            map.addProperty("BDVer", bdVer);
            map.addProperty("BDID", bdId);
            map.addProperty("RepairType", type);
            map.addProperty("RepairLevel", level);
            map.addProperty("FaultDesc", desc);
            map.addProperty("Remark", etRemark.getText().toString().trim());
            requestAskRepair(map);
        });
        return new FreeUI_AddViewEntity("header", llMain);
    }

    private void requestAskRepair(JsonObject map) {
        NetUtils.requestGetNet(this, "EMS_RepairCall", map, new FreeUI_DialogEntityCallBack<BaseResponseBean<?>>(
                new TypeToken<BaseResponseBean<?>>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<BaseResponseBean<?>> response) {
                if (response.body().isSuccess(getApplicationContext(), false, getSupportFragmentManager())) {
                    showToast("提交成功", true);
                    new Handler().postDelayed(MFG_AskRepairActivity.this::finish, 2000);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<?>> response) {
                super.onError(response);
                uploadLog(response.getException());
                loadError(response.getException(), "EMS_RepairCall");
            }
        });
    }

    @OnClick({R.id.flType, R.id.flLevel, R.id.flDesc})
    public void onViewClicked(View view) {
        if (MyUtils.isFastClick()){
            showToast("您点击的太快了",false);
            return;
        }
        switch (view.getId()) {
            case R.id.flType:
                if (typePop != null) {
                    if (typePop.isShowing()) {
                        typePop.dismiss();
                    } else {
                        FreeApi_PopUtils.setArrowShow(ivTypeArrow);
                        typePop.showAsDropDown(flType, 0, 0);
                    }
                }
                break;
            case R.id.flLevel:
                if (levelPop == null) {
                    List<String> levelList = new ArrayList<>();
                    levelList.add("高");
                    levelList.add("中");
                    levelList.add("低");
                    levelPop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flLevel.getWidth(), levelList, ivLevelArrow, (s, i) -> {
                        tvLevel.setText(s);
                    });
                }
                if (levelPop.isShowing()) {
                    levelPop.dismiss();
                } else {
                    FreeApi_PopUtils.setArrowShow(ivLevelArrow);
                    levelPop.showAsDropDown(flLevel, 0, 0);
                }
                break;
            case R.id.flDesc:
                if (descPop != null) {
                    if (descPop.isShowing()) {
                        descPop.dismiss();
                    } else {
                        FreeApi_PopUtils.setArrowShow(ivDescArrow);
                        descPop.showAsDropDown(flDesc, 0, 0);
                    }
                }
                break;
        }
    }
}
